#include "dbmodel.h"
#include "exception.h"

#include <QDebug>

DbModel::DbModel(QObject *parent)
    :QAbstractTableModel(parent),
      size(0),
      db(NULL)
{
    int r = sqlite3_open("secret.db", &db);
    if( r != SQLITE_OK )
        throw AppException("Failed to open db");
}

DbModel::~DbModel()
{
    if(this->db)
        sqlite3_close(db);
    if(this->list)
        delete [] list;
}

int DbModel::rowCount(const QModelIndex &parent) const
{
    return this->size;
}

int DbModel::columnCount(const QModelIndex &parent) const
{
    Q_UNUSED(parent);
    return 3;
}

QVariant DbModel::data(const QModelIndex &index, int role) const
{
    if (role == Qt::DisplayRole)
    {
        Item item = this->list[index.row()];
        int c = index.column();
        if(c == 0)
            return QString::fromStdString(item.id);
        if(c == 1)
            return QString::fromStdString(item.content);
        if(c == 2)
            return QString::fromStdString(item.remark);
    }
    return QVariant();
}

QVariant DbModel::headerData(int section, Qt::Orientation orientation, int role) const
{
    if (role != Qt::DisplayRole)
        return QVariant();

    if (orientation == Qt::Horizontal) {
        switch (section) {
        case 0:
            return tr("ID");
        case 1:
            return tr("Remark");
        case 2:
            return tr("Create Date");
        default:
            return QVariant();
        }
    }
    return QVariant();
}

//int loadItem( void * para, int n_column, char ** column_value, char ** column_name )
//{
//    int i;
//    for(i=0;i<n_column;i++){
//        printf("\t%s",column_value[i]);
//    }
//    printf("\n");

//    return 0;
//}

int DbModel::query()
{
    char *errMsg;
    char **dbresult;
    int nrow, ncolumn;

    int ret = sqlite3_get_table(this->db,
                                "select id, version, mime, create_date, content, remark from img",
                                &dbresult, &nrow, &ncolumn, &errMsg);
    if(ret != SQLITE_OK)
    {
        qDebug() << "Query error:" << errMsg;
        this->size = 0;
        if(this->list)
            delete [] this->list;
        this->list = NULL;
    }
    else
    {
        this->size = nrow;
        Item *newResult = new Item[this->size];
        int index = ncolumn;
        for(int i = 0; i < nrow; i++){
            Item *item = &newResult[i];
            item->id = dbresult[index + 0];
            item->content = dbresult[index + 1];
            item->remark = dbresult[index + 2];
            index += ncolumn;

        }
        if(this->list)
            delete [] this->list;
        this->list = newResult;
    }
    sqlite3_free_table(dbresult);
    sqlite3_free(errMsg);
}
